<template>
  <el-dialog :title="title" :visible.sync="visible" width="500px" :before-close="handleClose">
    <el-form :rules="rules" ref="formData" :model="formData" label-width="100px" label-position="right" style="width: 400px" status-icon>
      <el-form-item label="角色名称：" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <el-input type="textarea" v-model="formData.remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('formData')" size="mini" :loading="loadinge">确定</el-button>
        <el-button size="mini" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>

import api from '@/api/role'

export default {
  props: {
    title: { // 弹窗的标题
      type: String,
      default: ''
    },
    visible: { // 弹出窗口，true弹出
      type: Boolean,
      default: false
    },
    formData: { // 提交表单数据
      type: Object,
      default: {}
    },
    loadinge: false,
    remoteClose: Function // 用于关闭窗口
  },

  data() {
    return {
      rules: {
        name: [ // prop值
          {required: true, message: '请输入角色名称', trigger: 'blur'},
        ],
      }
    }
  },

  methods: {
    // 提交表单数据
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 校验通过，提交表单数据
          this.submitData()
        } else {
          // console.log('error submit!!');
          return false;
        }
      })
    },

    async submitData() {
      let response = null
      this.loadinge = true
      if (this.formData.id) {
        // 编辑
        response = await api.update(this.formData)
      } else {
        // 新增
        response = await api.add(this.formData)
      }

      if (response.code === 20000) {
        this.loadinge = false
        //   提示信息
        this.$message({message: '保存成功', type: 'success'})
        // 关闭窗口
        this.handleClose()
      } else {
        this.loadinge = false
        this.$message({message: '保存失败', type: 'error'})
      }
      this.loadinge = false
    },

    handleClose() {
      this.$refs['formData'].resetFields()
      this.remoteClose()
    }
  }
}
</script>
